<?php

namespace haibao\cms\data\activity;

use haibao\cms\model\filter\activity\Activity as ActivityFilter;

class Activity extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\activity\Activity');
    }
    
    public function addActivityData($addActivityModel){
        $this->beginTranscation();
        try{
            $this->add($addActivityModel);
        } catch(\Exception $e){
            throw $e;
        }
        $this->endtranscation();
        return $addActivityModel;
    }
    
    public function updateActivityData($editActivityModel){
        $activityModel = $this->packActivityFilter($editActivityModel);
        $this->beginTranscation();
        try{
            $this->updateById($editActivityModel->Id,$activityModel);
        } catch(\Exception $e){
            throw $e;
        }
        $this->endtranscation();
    }
    private function packActivityFilter($editActivityModel){
        $activityFilter = new ActivityFilter;
        $activityFilter = array(
            ActivityFilter::CONDITION_FIELD_NAME_TITLE =>$editActivityModel->Title,
            ActivityFilter::CONDITION_FIELD_NAME_STARTTIME =>$editActivityModel->StartTime,
            ActivityFilter::CONDITION_FIELD_NAME_ENDTIME =>$editActivityModel->EndTime,
            ActivityFilter::CONDITION_FIELD_NAME_PRONUM =>$editActivityModel->ProNum,
            ActivityFilter::CONDITION_FIELD_NAME_STATUS =>$editActivityModel->Status,
            ActivityFilter::CONDITION_FIELD_NAME_CREATEBY =>$editActivityModel->CreateBy,
            ActivityFilter::CONDITION_FIELD_NAME_CREATETIME =>$editActivityModel->CreateTime,
            ActivityFilter::CONDITION_FIELD_NAME_PROTYPE =>$editActivityModel->ProType,
        );
        return $activityFilter;
    }
    
    /**
     * 更新活动表里面的奖品数量
     * @param  $id 活动ID
     * @param string $operateType 其中，1为-num;2为+num;3为-或+
     */
    
    public function updateActivityPrizeNumById($id,$num,$operateType,$restNum){
        if($operateType == 2){
            $sql="update Activity set PrizeNum = PrizeNum + ".$num.",RestPrizeNum = RestPrizeNum + ".$num." where Id=".$id;
            $this->query($sql);
        }elseif ($operateType == 1){
            $sql="update Activity set PrizeNum = PrizeNum - ".$num.",RestPrizeNum = RestPrizeNum - ".$num." where Id=".$id;
            $this->query($sql);
        }elseif ($operateType == 3){
            $editRestPrizeNum = 0;
            if($restNum > $num){
                $editRestPrizeNum = $restNum - $num;
                $sql="update Activity set PrizeNum = PrizeNum - ".$editRestPrizeNum.",RestPrizeNum = RestPrizeNum - ".$editRestPrizeNum." where Id=".$id;
            }elseif ($restNum < $num){
                $editRestPrizeNum = $num - $restNum;
                $sql="update Activity set PrizeNum = PrizeNum + ".$editRestPrizeNum.",RestPrizeNum = RestPrizeNum + ".$editRestPrizeNum." where Id=".$id;
            }
        }
    }
}